import {
	baseURL
} from '@/api/env.js'


const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync('token')
	} catch (e) {}
	return token
}

function download(data) {
	const downloadTask = uni.downloadFile({
		url: baseURL + data.url,
		success: (data) => {
			var tempFilePath = data.tempFilePath;
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '文件下载完成'// + tempFilePath, //保存路径
			// });
			//打开文档查看
			uni.openDocument({
				filePath: tempFilePath,
				success: function(res) {
					// console.log('打开文档成功');
				},
				fail: (res) => {
					uni.showToast({
						icon: 'none',
						title: '打开文件失败',
					});
				}
			});
		},
		fail: (err) => {
			console.log(err);
			uni.showToast({
				icon: 'none',
				title: '失败请重新下载',
			});
		},
		complete: (res) => {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '下载完成',
			// });
		}
	});
	downloadTask.onProgressUpdate((res) => {
		console.log('下载进度' + res.progress);
		console.log('已经下载的数据长度' + res.totalBytesWritten);
		console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
	});
}

function sendRequest(opts) {
	opts = opts || {};
	opts.url = opts.url || '';
	opts.method = opts.method || 'GET';
	opts.param = opts.param || {};
	opts.header = opts.header || {
		"Content-Type": "application/json;charset=utf-8",
	};
	opts.responseType = opts.responseType || 'text';
	opts.withCredentials = opts.withCredentials || false; //跨域请求时是否携带凭证（cookies）
	opts.tt = opts.tt || false; //是否不需要携带token
	var token = getTokenStorage();
	// console.log("本地存储的token：" + token + "--" + opts.tt);
	if (!opts.tt) {
		if (token == '') {
			uni.showToast({
				title: '您还未登录',
				icon: 'none'
			});
			uni.reLaunch({
				url: '/pages/login/login'
			})
			return null;
		}
		opts.header.Authorization = token
		// console.log("参数："+opts.header)
	}
	// console.log("参数：" + JSON.stringify(opts.param))
	var promiss = new Promise(function(resolve, reject) {
		uni.showLoading({
			title: "加载中"
		})
		uni.request({
			url: baseURL + opts.url,
			data: opts.param,
			header: opts.header,
			method: opts.method,
			withCredentials: opts.withCredentials,
			responseType: opts.responseType,
			success: function(res) {
				uni.hideLoading();
				// console.log('res:' + JSON.stringify(res))
				if (res.statusCode == 200) {
					// console.log("请求成功" + JSON.stringify(res.data));
					if (res.data.flag) {
						resolve(res.data.data);
					} else {
						console.log("返回结果是查询失败呀：" + res.data.flag)
						reject(res.data.msg);
					}
				} else if (res.statusCode == 404) {
					reject("网络连接异常,请求失败");
				} else if (res.statusCode == 401) {
					reject("未授权");
				} else if (res.statusCode == 403) {
					reject("禁止访问");
				} else if (res.statusCode == 201) {
					uni.showToast({
						title: '您还未登录',
						icon: 'none'
					});
					uni.reLaunch({
						url: '/pages/login/login'
					})
				} else {
					reject("数据交互异常");
				}
			},
			fail: function(res) {
				uni.hideLoading();
				// uni.showToast({
				// 	title: "网络出错",
				// 	icon: 'none'
				// });
				reject("网络出错");
			}
		})
		// }).catch((err) => {
		// 	console.log('Error:' + err);
		// 	uni.showToast({
		// 		title: err,
		// 		icon: 'none'
		// 	});
	})
	// .then(
	// 	(val) => {
	// 		console.log(val)
	// 	}, (err) => {
	// 		console.log('Error:' + err);
	// 		uni.showToast({
	// 			title: err,
	// 			icon: 'none'
	// 		});
	// 	})
	return promiss;
}


function sendRequest_page(opts) {
	opts = opts || {};
	opts.url = opts.url || '';
	opts.method = opts.method || 'GET';
	opts.param = opts.param || {};
	opts.header = opts.header || {
		"Content-Type": "application/json;charset=utf-8",
	};
	opts.responseType = opts.responseType || 'text';
	opts.withCredentials = opts.withCredentials || false; //跨域请求时是否携带凭证（cookies）
	opts.tt = opts.tt || false; //是否不需要携带token
	var token = getTokenStorage();
	if (!opts.tt) {
		if (token == '') {
			uni.showToast({
				title: '您还未登录',
				icon: 'none'
			});
			uni.reLaunch({
				url: '/pages/login/login'
			})
			return null;
		}
		opts.header.Authorization = token
	}
	var promiss = new Promise(function(resolve, reject) {
		uni.showLoading({
			title: "加载中"
		})
		uni.request({
			url: baseURL + opts.url,
			data: opts.param,
			header: opts.header,
			method: opts.method,
			withCredentials: opts.withCredentials,
			responseType: opts.responseType,
			success: function(res) {
				uni.hideLoading();
				if (res.statusCode == 200) {
					resolve(res.data);
				} else if (res.statusCode == 404) {
					reject("网络连接异常,请求失败");
				} else if (res.statusCode == 401) {
					reject("未授权");
				} else if (res.statusCode == 403) {
					reject("禁止访问");
				} else if (res.statusCode == 201) {
					uni.showToast({
						title: '您还未登录',
						icon: 'none'
					});
					uni.reLaunch({
						url: '/pages/login/login'
					})
				} else {
					reject("数据交互异常");
				}
			},
			fail: function(res) {
				uni.hideLoading();
				reject("网络出错");
			}
		})
	})
	return promiss;
}


function get(opts) {
	opts.method = 'GET';
	return this.sendRequest(opts);
}

function post(opts) {
	opts.method = 'POST';
	return this.sendRequest(opts);
}

function post_page(opts) {
	opts.method = 'POST';
	return this.sendRequest_page(opts);
}

function put(opts) {
	opts.method = 'PUT';
	return this.sendRequest(opts);
}


module.exports.download = download
module.exports.sendRequest = sendRequest
module.exports.sendRequest_page = sendRequest_page
module.exports.post = post
module.exports.post_page = post_page
module.exports.get = get
module.exports.put = put
module.exports.baseURL = baseURL